from django.core.management.base import BaseCommand, CommandError
import os
import sys
import json
import tempfile
import subprocess
from django.conf import settings
from datetime import datetime
from pathlib import Path

class Command(BaseCommand):
    help = '解析README-zh.md文件，提取MCP服务器信息并存入数据库'

    def add_arguments(self, parser):
        parser.add_argument('--readme-path', type=str, help='README-zh.md文件路径')
        parser.add_argument('--output-json', type=str, help='输出JSON文件路径')
        parser.add_argument('--verbose', action='store_true', help='显示详细日志')

    def handle(self, *args, **options):
        # 获取README文件路径
        readme_path = options.get('readme_path')
        if not readme_path:
            # 尝试在项目根目录下查找
            possible_paths = [
                os.path.join(settings.BASE_DIR, '..', 'awesome-mcp-servers', 'README-zh.md'),
                os.path.join(settings.BASE_DIR, '..', 'README-zh.md'),
                os.path.join(settings.BASE_DIR, 'README-zh.md'),
            ]
            
            for path in possible_paths:
                if os.path.exists(path):
                    readme_path = path
                    self.stdout.write(f"找到README文件: {readme_path}")
                    break
            
            if not readme_path:
                raise CommandError("无法找到README-zh.md文件，请使用--readme-path指定路径")
        
        # 检查README文件存在
        if not os.path.exists(readme_path):
            raise CommandError(f"README文件不存在: {readme_path}")
        
        # 获取输出JSON路径
        output_json = options.get('output_json')
        if not output_json:
            # 设置默认输出到backend/scripts/mcp_server_list.json
            output_json = os.path.join(settings.BASE_DIR, 'scripts', 'mcp_server_list.json')
            # 确保目录存在
            os.makedirs(os.path.dirname(output_json), exist_ok=True)
        
        # 运行解析脚本
        script_path = os.path.join(settings.BASE_DIR, 'scripts', 'parse_readme.py')
        db_path = os.path.join(settings.BASE_DIR, 'db.sqlite3')
        
        verbose_flag = '--verbose' if options.get('verbose') else ''
        
        cmd = [
            sys.executable, script_path,
            '--readme', readme_path,
            '--output', output_json,
            '--db', db_path
        ]
        
        if verbose_flag:
            cmd.append(verbose_flag)
        
        self.stdout.write(f"执行命令: {' '.join(cmd)}")
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
            
            if result.returncode != 0:
                self.stderr.write(f"解析脚本执行失败: {result.stderr}")
                raise CommandError("解析脚本执行失败")
            
            # 成功执行
            self.stdout.write(result.stdout)
            
            # 读取JSON文件获取结果数据
            with open(output_json, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            self.stdout.write(self.style.SUCCESS(
                f"解析完成: 共 {data.get('count', 0)} 个MCP服务器，"
                f"更新时间: {data.get('last_updated')}"
            ))
            
        except Exception as e:
            self.stderr.write(f"执行失败: {str(e)}")
            raise CommandError(f"执行失败: {str(e)}") 